<template>
  <div v-if="visible" class="modal-overlay" @click="handleClose">
    <div class="modal-content" @click.stop>
      <div class="modal-header">
        <h3>{{ isEdit ? '编辑项目' : '添加项目' }}</h3>
        <button class="close-button" @click="handleClose">×</button>
      </div>

      <form @submit.prevent="handleSubmit" class="project-form">
        <div class="form-grid">
          <!-- 项目名称 -->
          <div class="form-group full-width">
            <label for="name">项目名称 *</label>
            <input
              id="name"
              v-model="formData.name"
              type="text"
              required
              placeholder="请输入项目名称"
              :disabled="!!isEdit"
              :readonly="!!isEdit"
            />
            <small v-if="isEdit" class="field-hint">项目名称创建后不可修改</small>
          </div>

          <!-- 项目描述 -->
          <div class="form-group full-width">
            <label for="description">项目描述</label>
            <textarea
              id="description"
              v-model="formData.description"
              rows="3"
              placeholder="请输入项目描述..."
            ></textarea>
          </div>

          <!-- 开始日期 -->
          <div class="form-group">
            <label for="start_date">开始日期</label>
            <input id="start_date" v-model="formData.start_date" type="date" />
          </div>

          <!-- 结束日期 -->
          <div class="form-group">
            <label for="end_date">结束日期</label>
            <input
              id="end_date"
              v-model="formData.end_date"
              type="date"
              :min="formData.start_date || undefined"
            />
          </div>

          <!-- 预算 -->
          <div class="form-group">
            <label for="budget">预算</label>
            <input
              id="budget"
              v-model="budgetValue"
              type="number"
              step="0.01"
              min="0"
              placeholder="0.00"
            />
          </div>

          <!-- 颜色 -->
          <div class="form-group">
            <label for="color">颜色</label>
            <div class="color-input-group">
              <input
                id="color"
                v-model="formData.color"
                type="color"
                class="color-picker"
              />
              <input
                v-model="formData.color"
                type="text"
                class="color-text"
                placeholder="#007aff"
              />
            </div>
          </div>

          <!-- 项目状态 -->
          <div class="form-group">
            <label class="checkbox-label">
              <input type="checkbox" v-model="formData.is_active" />
              项目进行中
            </label>
          </div>
        </div>

        <!-- 预览 -->
        <div class="preview-section">
          <h4>预览</h4>
          <div class="project-preview">
            <div class="project-info-preview">
              <div class="project-name-preview">
                {{ formData.name || "项目名称" }}
              </div>
              <div
                v-if="formData.description"
                class="project-description-preview"
              >
                {{ formData.description }}
              </div>
              <div class="project-meta-preview">
                <span v-if="formData.budget" class="project-budget-preview">
                  预算: ¥{{ formatAmount(parseFloat(formData.budget) || 0) }}
                </span>
                <span
                  class="project-status-preview"
                  :class="{ active: formData.is_active }"
                >
                  {{ formData.is_active ? "进行中" : "已结束" }}
                </span>
              </div>
            </div>
          </div>
        </div>

        <div class="form-actions">
          <button type="button" class="btn-cancel" @click="handleClose">
            取消
          </button>
          <button type="submit" class="btn-primary" :disabled="loading">
            {{ loading ? (isEdit ? "更新中..." : "创建中...") : (isEdit ? "更新项目" : "创建项目") }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from "vue";
import { useAccountingStore } from "@/stores/accounting";
import { getCurrentDate } from "@/utils/dateUtils";
import type { ProjectCreate, ProjectUpdate, ProjectResponse } from "@/types/accounting";

interface Props {
  visible: boolean;
  editData?: ProjectResponse | null;
}

interface Emits {
  (e: "update:visible", visible: boolean): void;
  (e: "close"): void;
  (e: "success"): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const accountingStore = useAccountingStore();

// 编辑模式状态
const isEdit = computed(() => props.editData && props.editData.id);

// 表单数据
const formData = reactive({
  name: "",
  description: "",
  start_date: getCurrentDate(),
  end_date: null as string | null,
  budget: "",
  color: "#007aff",
  is_active: true,
});

// 加载状态
const loading = ref(false);

// 预算值处理
const budgetValue = computed({
  get: () => formData.budget,
  set: (value) => {
    formData.budget = value || "";
  },
});

// 监听visible变化，重置表单
watch(
  () => props.visible,
  (newVisible) => {
    if (newVisible) {
      resetForm();
    }
  },
);

// 重置表单
function resetForm() {
  if (props.editData) {
    // 编辑模式：填充现有数据
    formData.name = props.editData.name;
    formData.description = props.editData.description || "";
    formData.start_date = props.editData.start_date || getCurrentDate();
    formData.end_date = props.editData.end_date || null;
    formData.budget = props.editData.budget || "";
    formData.color = props.editData.color || "#007aff";
    formData.is_active = props.editData.is_active;
  } else {
    // 添加模式：清空表单
    formData.name = "";
    formData.description = "";
    formData.start_date = getCurrentDate();
    formData.end_date = null;
    formData.budget = "";
    formData.color = "#007aff";
    formData.is_active = true;
  }
}

// 格式化金额
function formatAmount(amount: number): string {
  return amount.toFixed(2);
}

// 处理关闭
function handleClose() {
  emit("update:visible", false);
  emit("close");
}

// 处理提交
async function handleSubmit() {
  if (!formData.name) {
    alert("请填写项目名称");
    return;
  }

  try {
    loading.value = true;

    // 验证日期
    if (formData.start_date && formData.end_date) {
      const startDate = new Date(formData.start_date);
      const endDate = new Date(formData.end_date);
      if (startDate > endDate) {
        alert("结束日期不能早于开始日期");
        return;
      }
    }

    // 验证预算
    if (formData.budget) {
      const budget = parseFloat(formData.budget);
      if (isNaN(budget) || budget < 0) {
        alert("请输入有效的预算金额");
        return;
      }
    }

    if (isEdit.value && props.editData) {
      // 编辑模式：更新项目
      const updateData: ProjectUpdate = {
        name: formData.name.trim() || undefined,
        description: formData.description.trim() || undefined,
        start_date: formData.start_date || undefined,
        end_date: formData.end_date || undefined,
        budget: formData.budget || undefined,
        color: formData.color || undefined,
        is_active: formData.is_active,
      };
      await accountingStore.updateProject(props.editData.id, updateData);
    } else {
      // 添加模式：创建项目
      const createData: ProjectCreate = {
        name: formData.name.trim(),
        description: formData.description.trim() || null,
        start_date: formData.start_date || null,
        end_date: formData.end_date || null,
        budget: formData.budget || null,
        color: formData.color || "#007aff",
      };
      await accountingStore.createProject(createData);
    }

    // 成功后关闭模态框
    emit("success");
    emit("close");
  } catch (error) {
    console.error(isEdit.value ? "更新项目失败:" : "创建项目失败:", error);
    alert(isEdit.value ? "更新项目失败，请重试" : "创建项目失败，请重试");
  } finally {
    loading.value = false;
  }
}
</script>

<style lang="scss" scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
  backdrop-filter: blur(5px);
}

.modal-content {
  background: var(--el-bg-color-overlay);
  backdrop-filter: blur(10px);
  border-radius: var(--el-border-radius-base);
  box-shadow: var(--el-box-shadow-light);
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  border: 1px solid var(--el-border-color);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid var(--el-border-color);

  h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: var(--el-text-color-primary);
    font-family:
      -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  }
}

.close-button {
  background: none;
  border: none;
  font-size: 20px;
  color: var(--el-text-color-secondary);
  cursor: pointer;
  padding: 4px;
  border-radius: var(--el-border-radius-small);
  transition: all 0.3s ease;

  &:hover {
    background: rgba(0, 0, 0, 0.1);
    color: var(--el-text-color-primary);
  }
}

.project-form {
  padding: 20px;
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;

  .full-width {
    grid-column: 1 / -1;
  }
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;

  label {
    font-size: 14px;
    font-weight: 500;
    color: var(--el-text-color-primary);
    font-family:
      -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  }

  .checkbox-label {
    flex-direction: row;
    align-items: center;
    gap: 8px;

    input[type="checkbox"] {
      width: auto;
    }
  }

  .field-hint {
    font-size: 12px;
    color: var(--el-color-warning);
    margin-top: 4px;
    font-style: italic;
  }
}

input[type="text"],
input[type="number"],
input[type="date"],
input[type="color"],
textarea {
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: var(--el-border-radius-small);
  color: var(--el-text-color-primary);
  font-size: 14px;
  padding: 8px 16px;
  outline: none;
  transition: all 0.3s ease;
  font-family:
    -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;

  &:focus {
    border-color: var(--el-color-primary);
    box-shadow: 0 0 0 3px rgba(var(--el-color-primary-rgb), 0.1);
  }

  &::placeholder {
    color: var(--el-text-color-placeholder);
  }
}

textarea {
  resize: vertical;
  min-height: 80px;
}

.color-input-group {
  display: flex;
  gap: 8px;
  align-items: center;

  .color-picker {
    width: 50px;
    height: 36px;
    border-radius: var(--el-border-radius-small);
    border: 1px solid var(--el-border-color);
    cursor: pointer;

    &::-webkit-color-swatch-wrapper {
      padding: 0;
    }

    &::-webkit-color-swatch {
      border: none;
      border-radius: var(--el-border-radius-small);
    }
  }

  .color-text {
    flex: 1;
  }
}

.preview-section {
  margin: 24px 0;
  padding: 16px;
  background: var(--el-bg-color-overlay);
  border-radius: var(--el-border-radius-small);

  h4 {
    margin: 0 0 8px 0;
    font-size: 14px;
    font-weight: 500;
    color: var(--el-text-color-primary);
    font-family:
      -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  }
}

.project-preview {
  padding: 8px;
  background: var(--el-bg-color);
  border-radius: var(--el-border-radius-small);
  border: 1px solid var(--el-border-color);
}

.project-info-preview {
  flex: 1;
}

.project-name-preview {
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  margin: 0 0 4px 0;
  font-family:
    -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}

.project-description-preview {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  margin: 0 0 8px 0;
}

.project-meta-preview {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.project-budget-preview {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  background: var(--el-bg-color-overlay);
  padding: 4px 8px;
  border-radius: var(--el-border-radius-small);
}

.project-status-preview {
  font-size: 14px;
  padding: 4px 8px;
  border-radius: var(--el-border-radius-small);
  font-weight: 500;

  &.active {
    background: rgba(34, 197, 94, 0.1);
    color: #22c55e;
  }

  &:not(.active) {
    background: rgba(156, 163, 175, 0.1);
    color: #9ca3af;
  }
}

.form-actions {
  display: flex;
  justify-content: space-between;
  gap: 16px;
  margin-top: 24px;

  button {
    flex: 1;
    padding: 12px 20px;
    border: none;
    border-radius: var(--el-border-radius-small);
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
    font-family:
      -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;

    &:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }
  }
}

.btn-cancel {
  background: var(--el-bg-color);
  color: var(--el-text-color-secondary);
  border: 1px solid var(--el-border-color);

  &:hover:not(:disabled) {
    background: var(--el-bg-color-overlay);
    color: var(--el-text-color-primary);
  }
}

.btn-primary {
  background: var(--el-color-primary);
  color: white;

  &:hover:not(:disabled) {
    background: var(--el-color-primary-light-3);
    transform: translateY(-1px);
  }
}

@media (max-width: 768px) {
  .modal-content {
    width: 95%;
    max-width: none;
  }

  .form-grid {
    grid-template-columns: 1fr;
  }

  .color-input-group {
    flex-direction: column;
    align-items: stretch;

    .color-picker {
      width: 100%;
    }
  }

  .form-actions {
    flex-direction: column;
  }
}
</style>
